﻿<?php
require 'weather.php';
require 'location.php';

date_default_timezone_set('Asia/Hong_Kong');  //set time zone
define("TOKEN", "WeatherGod");
$max_size = 500000;

$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj->responseMsg();

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        logger("R ".$postStr);
        //extract post data
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE)
            {
                case "text":
                    $resultStr = $this->receiveText($postObj);
                    break;
                case "image":
                    $resultStr = $this->receiveImage($postObj);
                    break;
                case "location":
                    $resultStr = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    $resultStr = $this->receiveVoice($postObj);
                    break;
                case "video":
                    $resultStr = $this->receiveVideo($postObj);
                    break;
                default:
                    $resultStr = "unknow msg type";
                    break;
            }
            logger("T ".$resultStr);
            echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    private function receiveText($object)
    {
        $funcFlag = 0;
        $keyword = trim($object->Content);
        $resultStr = "";
        $cityArray = array();
        $contentStr = "";
        $needArray = false;
        
        if ($keyword === "Hello2BizUser"){
            $contentStr = "你好，欢迎关注天气神。\n微信平台上最强大最好用最受欢迎的天气查询应用\n获取使用方法请发送 ? 或 help 或 sos 或 “帮助”。";
        }
        else if(preg_match("/^\?|？|help|sos|帮助$/",strtolower($keyword))){
            //$contentStr = "★★★★天气神★★★★ 微信平台上最强大最好用最受欢迎的天气查询应用\n使用方法：\n1.发送城市名,如“深圳”;\n2.发送电话区号,如“0755”;\n3.发送全拼,如“shenzhen”;\n4.发送简拼,如“sz”;\n5.发送邮政编码,如518057;\n6.发送位置,点击“＋”,然后选择“位置”,等待微信确定你的位置后,点击“发送”;\n7.发送语音,点击“按住说话”,说出你的地址,然后松开结束录音;\n8.更多玩法,敬请期待……";
            $contentStr = "★★★★天气神★★★★ 微信平台上最强大最好用最受欢迎的天气查询应用\n使用方法：\n1.发送城市名,如“深圳”;\n2.发送电话区号,如“0755”;\n3.发送全拼,如“shenzhen”;\n4.发送邮政编码,如518000;\n…\n99.更多玩法,敬请期待……";
        }
        else if(preg_match("/^\+[\x{4e00}-\x{9fa5}]+$/u",$keyword)){	//提交城市
            $contentStr = "[".substr($keyword,1,strlen($keyword)).'] 已提交，我们将尽快处理，谢谢您的支持';
            $funcFlag = 1;
        }
        else if(preg_match("/^\d{3,5}$/",$keyword)){			//电话号码区号
            $cityArray = fromKeywordToCode("teleCode", $keyword);
        }
        else if (preg_match("/^\d{6}$/",$keyword)){				//邮政编码
            $cityArray = fromKeywordToCode("postCode", $keyword);
        }
        // else if (preg_match("/^[A-Za-z]{2}$/",$keyword)){	//城市简拼
            // echo($keyword.'是城市简拼');
        // }
        else if (preg_match("/^[A-Za-z]{3,}$/",$keyword)){		//城市全拼
            $cityArray = fromKeywordToCode("quanPing", $keyword);
        }
        else if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$keyword)){	//汉字
            $cityArray = fromKeywordToCode("cityName", $keyword);
        }
        else {
            $contentStr = $keyword.'不是合法的查询指令';
            $funcFlag = 1;
        }

        //回复格式
        //1. 没有获得结果
        if (count($cityArray) == 0) {
			if (empty($contentStr)){
				$contentStr = "很抱歉，[".$keyword."]未被收录！如你确定它是有效指令，请发送  +".$keyword."  我们将收录它，谢谢您的支持！";
            }
			$resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        }
        //2. 获得一个结果，执行天气查询
        else if (count($cityArray) == 1){
            if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$keyword)){$needArray = true;} //汉字查询均返回图文
            $cityCode = current($cityArray);
			replaceUserRecord($object->FromUserName, $cityCode);//更新数据库中查询记录
            $weatherRealTime = getWeather_realTime($cityCode, $needArray);
            $weatherSixDays = getWeather_sixdays($cityCode, $needArray);
            $copyRight = copyRight($needArray);
            if(is_array($weatherRealTime) && is_array($weatherSixDays) && is_array($weatherSixDays)){
                $resultStr = $this->transmitNews($object, array_merge_recursive($weatherRealTime, $weatherSixDays, $copyRight), $funcFlag);
            }
            else
            {
                $resultStr = $this->transmitText($object, $weatherRealTime.$weatherSixDays.$copyRight, $funcFlag);
            }
        }
        //3. 多个结果表明重复
        else {
            $cities = "匹配多个，请再次输入：";
            while(list($key, $val)= each($cityArray)) {
                $cities .= "\n".$key;
            }
            $contentStr = $cities;
            $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        }

        //Content 消息内容，大小限制在2048字节，字段为空为不合法请求
        return $resultStr;
    }

    private function receiveImage($object)
    {
        $contentStr = "receive a picture, url: ".$object->PicUrl;
        $resultStr = $this->transmitText($object, $contentStr);
        return $resultStr;
    }

    private function receiveLocation($object)
    {
        $contentStr = "receive a location, 经度:".$object->Location_X." 纬度:".$object->Location_Y." 位置:".$object->Label;
        $resultStr = $this->transmitText($object, $contentStr);
        return $resultStr;
    }
	
    private function receiveVoice($object)
    {
		$cityCode = searchUserRecord($object->FromUserName);
		// $contentStr = "请先体验一次本神的天气查询服务，再来呼叫我吧！".$cityCode;
		// $resultStr = $this->transmitText($object, $contentStr);
		
		if (empty($cityCode)){
			$contentStr = "receive a voice, MediaId: ".$object->MediaId;
			$contentStr = "请先体验一次本神的天气查询服务，再来呼叫我吧！";
			$resultStr = $this->transmitText($object, $contentStr);
		}
		else{
			$needArray = false;
            $weatherRealTime = getWeather_realTime($cityCode, $needArray);
            $weatherSixDays = getWeather_sixdays($cityCode, $needArray);
            $copyRight = copyRight($needArray);
            if(is_array($weatherRealTime) && is_array($weatherSixDays) && is_array($weatherSixDays)){
                $resultStr = $this->transmitNews($object, array_merge_recursive($weatherRealTime, $weatherSixDays, $copyRight), $funcFlag);
            }
            else
            {
                $resultStr = $this->transmitText($object, $weatherRealTime.$weatherSixDays.$copyRight, $funcFlag);
            }
		}
        return $resultStr;
    }
	
    private function receiveVideo($object)
    {
        $contentStr = "receive a video, url: ".$object->MediaId;
        $resultStr = $this->transmitText($object, $contentStr);
        return $resultStr;
    }
	
    private function transmitText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }

    private function transmitNews($object, $arr_item, $flag = 0)
    {
        //首条标题28字，其他标题39字
        if(!is_array($arr_item))
            return;

        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        var_dump($arr_item);
        $item_str = "";
        foreach ($arr_item as $item)
            $item_str .= sprintf($itemTpl, $item['title'], $item['description'], $item['pic'], $item['url']);

        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
<FuncFlag>%s</FuncFlag>
</xml>";


        $resultStr = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item), $flag);
        return $resultStr;
    }

}

function logger($log_content)
{
    if($_SERVER['SERVER_NAME'] == "txw1958.sinaapp.com"){
        sae_set_display_errors(false);//关闭信息输出
        sae_debug($log_content);//记录日志
        sae_set_display_errors(true);
    }
    else {
        Global $max_size;
        $log_filename = date("Ymd").".xml";
        if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);sleep(1);}
        file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
    }
}

function customReply($keyword)
{
    if ((double)$keyword > 0 and (double)$keyword < 200){
        return "Message: ".$keyword;
    }else{
        return "Unknown: ".$keyword;
    }
}

function copyRight($returnArray)
{
    $copyRightArray = array();
    //$copyRightArray[] = array("title"=>"天界神仙政府驻腾讯微信大使天气神", "description"=>"", "pic"=>"", "url" =>"");
    $copyRightArray[] = array("title"=>"方倍软件工作室 版权所有", "description"=>"", "pic"=>"", "url" =>"");
    if($returnArray){
        return $copyRightArray;
    }else {
        return $copyRightArray[0]["title"];
    }
}

?>